package com.itheima.auth;

import com.itheima.pojo.UserInfo;
import com.itheima.support.SysConsts;
import com.itheima.utils.RedisUtil;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * 自定义用户加载
 * */
@Component
public class MyUserDetailsService implements UserDetailsService {

    /**
     * @param username 前端传过来
     * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //数据库查询用户信息
        UserInfo userInfo = RedisUtil.get(SysConsts.USER_INFO_PREX_KEY + username);
        if(userInfo != null){
            return new User(username,userInfo.getPassword(),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(userInfo.getAuthority()));
        }
        //构造空密码，让报错提示更优雅
        return new User(username,"", Collections.emptyList());
    }

}
